package com.glls.order.service.impl;

import com.glls.common.vo.OrderVo;
import com.glls.order.feign.AccountApi;
import com.glls.order.feign.StockApi;
import com.glls.order.mapper.OrderMapper;
import com.glls.order.service.AccountService;
import com.glls.order.service.OrderService;
import com.glls.order.service.StockService;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 *
 * @author junyang
 * @version 1.0.0
 * @date 2025/2/24 10:45
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private StockService stockService;

    @Resource
    private AccountService accountService;



    //第一种   没有事务控制  出现了 数据不一致的情况
    @Override
    public int addOrderWithNoTransaction(OrderVo order) {

        //添加订单
        int result = orderMapper.addOrder(order);

        //扣减库存
        int result2 = stockService.updateStock(order);

        //扣减余额   没有事务时     账户余额扣减异常  但是 第订单  和  库存却执行了  导致数据不一致
        int result3 = accountService.updateAccount(order);

        return result3;
    }



    //第二种情况  加事务控制
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)    // 这种写法 任何异常都会回滚
    public int addOrderWithLocalTransaction(OrderVo order) throws ClassNotFoundException {
        //添加订单
        int result = orderMapper.addOrder(order);

        //扣减库存
        int result2 = stockService.updateStock(order);

        //扣减余额
        int result3 = accountService.updateAccount(order);

        //默认情况下  遇到  检查时异常 不会滚 ，如要回滚   需要指定  rollbackFor = Exception.class
        //Class.forName("java.lang.String2");

        return result3;
    }


    @Resource
    private AccountApi accountApi;

    @Resource
    private StockApi stockApi;


    //演示 分布式事务
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    @GlobalTransactional   // 全局事务开启
    public int addOrderWithDistributeTransaction(OrderVo order) {

        //添加订单
        int result = orderMapper.addOrder(order);

        //扣减库存
        int result2 = stockApi.updateStock(order);

        //扣减余额
        int result3 = accountApi.updateAccount(order);


        return result3;

    }


}
